<template>
  <div v-loading="loading" v-if="drawerVisible">
    <el-drawer
      v-model="drawerVisible"
      :title="drawerTitle"
      direction="rtl"
      size="80%"
      class="script"
    >
      <template #header="{ titleId, titleClass }">
        <h4 :id="titleId" :class="titleClass">{{ drawerTitle }}</h4>
      </template>
      <quickQuery
        @debug="handleDebug"
        @query-com-value="handleQueryValue"
        :tabData="{ info: info, response }"
      />
      <template #footer>
        <el-button :disabled="formLoading" type="primary" @click="submitForm">{{
          drawerType == 'create' ? '添加' : '修改'
        }}</el-button>
        <el-button @click="drawerVisible = false">取 消</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import * as DebugApi from '@/api/debug'
import quickQuery from '../../debug/module/quickQuery.vue'
import { useAppStore } from '@/store/modules/app'
import { useDebugStore } from '@/store/modules/debug'
import { isValidDateTime } from '@/utils/dateUtil'
const drawerVisible = ref(false)
const drawerTitle = ref('自定义请求')
const drawerType = ref('')
const formLoading = ref(false)
const loading = ref(false)
const emit = defineEmits(['success'])
provide('isShowSaveInterfaceBtn', false)
const debugStore = useDebugStore()
const appStore = useAppStore()
let projectId = computed(() => appStore.getSelectProject)
const environmentId = computed(() => debugStore.getEnvironmentId)
const queryInfo = ref({} as any)
const info = ref({} as any)
const response = ref({} as any)
const currentRow = ref({} as any)
/** 打开弹窗 */
const open = async (row?: any) => {
  drawerVisible.value = true
  drawerType.value = 'create'
  reset()
  if (row) {
    currentRow.value = row
    drawerType.value = 'update'
    drawerTitle.value = row.name
    // 存储过的步骤
    if (row.config) {
      const config = JSON.parse(row.config)
      let headers = []
      if (config.auth) {
        headers = config.requestHeaderList.filter((k) => k.keyName != 'Authorization')
      }
      info.value = {
        query: {
          protocal: 'http',
          requestType: config.requestType,
          url: config.url
        },
        requestContentType: config.requestContentType,
        params: config.requestParamsList,
        bodyForm: [],
        body: config.requestBody,
        headers: headers,
        auth: config.auth,
        cookie: [],
        post: config.post
      }
    } else {
      // 新增的步骤
      info.value = row.queryInfo
      response.value = row.response
    }
    queryInfo.value = info.value
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const reset = () => {
  drawerTitle.value = '自定义请求'
  queryInfo.value = {}
  info.value = {}
  response.value = {}
  currentRow.value = {}
}
const handlePostData = (list) => {
  if (!list || !list.length) return []
  return list.map((item) => {
    return {
      stepId: item.stepId,
      type: item.type,
      status: item.status ? 0 : 1
    }
  })
}
/** 调试 */
const handleDebug = async () => {
  loading.value = true
  // 当前tab存储的请求信息
  try {
    let paramsValue = []
    if (
      ['form-data', 'x-www-form-urlencoded'].includes(queryInfo.value.requestContentType) &&
      queryInfo.value.bodyForm?.length
    ) {
      paramsValue = queryInfo.value.bodyForm || []
      paramsValue.forEach((item) => {
        if (isValidDateTime(item.keyValue)) {
          item.keyValue = encodeURI(item.keyValue)
        }
      })
    } else {
      paramsValue = queryInfo.value.params || []
      paramsValue.forEach((item) => {
        if (isValidDateTime(item.keyValue)) {
          item.keyValue = encodeURI(item.keyValue)
        }
      })
    }
    // headers处理 1.存在auth,Headers中有Authorization时进行替换，没有时进行添加2.不存在auth时，直接使用Headers
    let headers = [] as any
    if (queryInfo.value.auth) {
      if (!queryInfo.value.headers?.length) {
        headers = [
          {
            keyName: 'Authorization',
            keyValue: queryInfo.value.auth,
            keyType: 'string'
          }
        ]
      } else {
        const isHasAuthorization = queryInfo.value.headers.some((q) => q.keyName == 'Authorization')
        if (isHasAuthorization) {
          headers = queryInfo.value.headers.map((item) => {
            if (item.keyName == 'Authorization') {
              return {
                ...item,
                keyValue: queryInfo.value.auth,
                keyType: 'string'
              }
            }
            return item
          })
        } else {
          headers = [
            ...(queryInfo.value.headers || []),
            {
              keyName: 'Authorization',
              keyValue: queryInfo.value.auth,
              keyType: 'string'
            }
          ]
        }
      }
    } else {
      headers = [...(queryInfo.value.headers || [])]
    }
    const apiParams = {
      projectId: projectId.value,
      environmentId: environmentId.value,
      ...queryInfo.value.query,
      requestContentType: queryInfo.value.requestContentType || '',
      requestHeaderList: headers,
      requestParamsList: paramsValue,
      requestBodyList: [],
      requestBody: queryInfo.value.body || '',
      postProcessors: handlePostData(queryInfo.value.post)
    }
    let res = await DebugApi.apiDebug(apiParams)
    let {
      responseHeaders,
      responseContent,
      requestBody,
      requestHeaderList,
      requestParamsList,
      responseResult,
      responseCode,
      responseTime,
      responseSize,
      requestUrl,
      cookies,
      responseContentType,
      extractorResponse,
      assertInfos,
      imageUrl
    } = res
    /** 响应内容存储到对应tab */
    response.value = {
      requestHeaderList,
      requestBody,
      requestParamsList,
      responseHeaders,
      responseContent,
      extractorResponse,
      assertInfos,
      imageUrl,
      responseResult: {
        responseCode,
        responseTime,
        responseSize,
        responseResult,
        requestUrl,
        cookies,
        responseContentType
      }
    }
  } catch (error) {
    response.value = {
      requestHeaderList: [],
      requestBody: '',
      requestParamsList: [],
      responseHeaders: [],
      responseContent: '',
      extractorResponse: [],
      assertInfos: [],
      imageUrl: '',
      responseResult: {
        responseCode: '',
        responseTime: '',
        responseSize: '',
        responseResult: '',
        requestUrl: '',
        cookies: [],
        responseContentType: ''
      }
    }
  } finally {
    loading.value = false
  }
}

/** 请求form、参数等变化后，放到对应tab中 */
const handleQueryValue = (value) => {
  queryInfo.value = {
    query: value.query,
    requestContentType: value.requestContentType || '',
    params: value.params || [],
    bodyForm: value.bodyForm || [],
    body: value.json || '',
    headers: value.headers || [],
    auth: value.auth || '',
    cookie: value.cookies || [],
    post: value.post || []
  }
}
/** 提交 */
const submitForm = async () => {
  emit('success', { queryInfo: queryInfo.value, response: response.value, row: currentRow.value })
  drawerVisible.value = false
}
</script>

<style scoped>
:deep(.topBox) {
  padding-left: 10px;
}

:deep(.downBox) {
  padding-left: 10px;
}
</style>
